package service

import (
	"teacher-helper/dao"
	"teacher-helper/models"
	"teacher-helper/models/request"
)

func AddOneStuGrant(StuGrant models.SysStuGrant) error {
	return dao.DB.Create(&StuGrant).Error
}

func GetStuGrantList(queryInfo request.QueryInfo) (StuGrants []models.SysStuGrant, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		err = dao.DB.Preload("Student").Preload("Grant").Find(&StuGrants).Count(&total).Error
		return
	}
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&models.SysStuGrant{}).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Grant").Preload("Student").Find(&StuGrants).Error
	} else {
		if err = dao.DB.Model(&models.SysStuGrant{}).Where("stu_id like ?", queryInfo.Query+"%").Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("stu_id like ?", queryInfo.Query+"%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Grant").Preload("Student").Find(&StuGrants).Error
	}
	return
}

func UpdateStuGrant(StuGrant models.SysStuGrant) error {
	return dao.DB.Save(&StuGrant).Error
}

func DeleteStuGrant(id int) error {
	return dao.DB.Where("id = ?", id).Delete(&models.SysStuGrant{}).Error
}
